﻿using System;
using System.Threading.Tasks;
using ThresholdAssistant.Autofac;
using ThresholdAssistant.NLogSdk;
using Quartz;
using ThresholdAssistant.WebAPI.Models;
using ThresholdAssistant.WebAPI.Service;

namespace ThresholdAssistant.Handler
{
    /// <summary>
    /// 重置每日登录次数
    /// </summary>
    [DisallowConcurrentExecution] // 单线程执行
    public class DemoSyncHandler : IBaseJob, IJob, IBaseAutofac
    {
        /// <summary>
        /// 
        /// </summary>
        public string JobName => "示例job";

        /// <summary>
        /// 
        /// </summary>
        public string JobGroupName => "示例job";

        /// <summary>
        /// 
        /// </summary>
        public string JobDescption => "示例job";

        /// <summary>
        /// 
        /// </summary>
        public string Cron => CronConstant.DemoSyncCron;

        /// <summary>
        /// 
        /// </summary>
        public DemoService DemoService { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Execute(IJobExecutionContext context)
        {
            var now = DateTime.Now;
            var logLevel = NLog.LogLevel.Info;
            var log = new NLogModel()
            {
                Content = $"{JobName}, Running"
            };
            try
            {
                NLogUtil.Info($"{JobName}, Running");
                //业务代码
                await DemoService.ExecuteAsync();
            }
            catch (Exception ex)
            {
                log.Content += $" 出错了，{ex}";
                logLevel = NLog.LogLevel.Error;
            }
            log.TotalSeconds = DateTime.Now.Subtract(now).TotalSeconds;
            NLogUtil.SaveLog(logLevel, log);
            log = null;
        }
    }
}
